package com.wbs.shop.nuby.jsbridge;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;

import com.alibaba.fastjson.JSONObject;
import com.wbs.shop.nuby.R;
import com.wbs.shop.nuby.api.ApiHelper;
import com.wbs.shop.nuby.api.RxHelper;
import com.wbs.shop.nuby.api.RxSubscribe;
import com.wbs.shop.nuby.commom.Key;
import com.wbs.shop.nuby.jsbridge.core.BaseInjected;
import com.wbs.shop.nuby.jsbridge.core.JsCallback;
import com.wbs.shop.nuby.utils.ActivityManger;
import com.wbs.shop.nuby.utils.Logger;
import com.wbs.shop.nuby.utils.NubyLocalBroadcastManager;
import com.wbs.shop.nuby.utils.Utils;
import com.wbs.shop.nuby.view.activity.CashierActivity;
import com.wbs.shop.nuby.view.activity.CashierActivityPadActivity;
import com.wbs.shop.nuby.view.activity.MainActivity;
import com.wbs.shop.nuby.view.activity.SimpleCashierActivity;
import com.wbs.shop.nuby.view.dialog.AlertDialog;
import com.wbs.shop.nuby.view.listener.IWebView;
import com.wbs.shop.nuby.view.listener.OnSuccessListener;
import com.wbs.shop.nuby.view.listener.OnReloadListener;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.runtime.Permission;

import library.qrcode.zxing.QrCodeHelper;
import library.qrcode.zxing.QrCodeListener;

/**
 * Created by zhoucl on 2018/5/28 0028.
 */
public class EventInjected extends BaseInjected {
    private BroadcastReceiver mBroadcastReceiver;
    private OnSuccessListener mOnLoginSuccessListener;

    public EventInjected(IWebView webView) {
        super(webView);
        mBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (Key.ACTION_REFRESH_PAGE.equals(intent.getAction()) && isNotNullWebView()) {
                    try {
                        String url = intent.getStringExtra(Key.URL);
                        if (!TextUtils.isEmpty(url) && webViewWeak.get().getUrl().contains(url))
                            webViewWeak.get().reload();
                    } catch (Exception e) {
                        Logger.e(e);
                    }
                }
            }
        };
        NubyLocalBroadcastManager.registerEventReceiver(mBroadcastReceiver);
    }

    public void setOnLoginSuccessListener(OnSuccessListener onLoginSuccessListener) {
        mOnLoginSuccessListener = onLoginSuccessListener;
    }

//    public void refreshFlag() {
//        Logger.e("refreshFlag==>" + webViewWeak.get().getUrl());
//        NubyLocalBroadcastManager.unregisterReceiver(mBroadcastReceiver);
//        mBroadcastReceiver = new BroadcastReceiver() {
//            @Override
//            public void onReceive(Context context, Intent intent) {
//                Logger.e("refreshFlag  onReceive==>" + intent.getAction());
//                if (Key.ACTION_REFRESH_FLAG.equals(intent.getAction()) && isNotNullWebView()) {
//                    webViewWeak.get().reload();
//                }
//                NubyLocalBroadcastManager.unregisterReceiver(this);
//                mBroadcastReceiver = null;
//            }
//        };
//        NubyLocalBroadcastManager.registerRefreshReceiver(mBroadcastReceiver);
//    }

//    public void onSuccess() {
//        Logger.e("onSuccess==>" + webViewWeak.get().getUrl());
//        if (mOnLoginSuccessListener != null)
//            mOnLoginSuccessListener.onSuccess();
//        else
//            NubyLocalBroadcastManager.sendSuccessBroadcastSync();
//        finish();
//    }

    public void refreshPreviousPage() {
        Activity lastActivity = ActivityManger.getLastActivity();
        if (lastActivity != null && lastActivity instanceof OnReloadListener) {
            ((OnReloadListener) lastActivity).onReload();
        }
    }

    public void finish() {
        if (isNotNullWebView() && webViewWeak.get().getContext() instanceof Activity) {
            ((Activity) webViewWeak.get().getContext()).finish();
        }
    }

    public void refreshPage(JSONObject jsonObject) {
        NubyLocalBroadcastManager.sendRefreshPageBroadcastSync(jsonObject.getString(Key.URL));
    }

    public void loginSuccess() {
//        if (Utils.isPad()) {
//            goCashier();
//        } else {
        NubyLocalBroadcastManager.sendLoginSuccessBroadcastSync();
//        }
    }

    /**
     * 返回首页
     * int index
     * String goUrl
     */
    public void goIndex(JSONObject jsonObject) {
        if (isNotNullWebView()) {
            NubyLocalBroadcastManager.sendGoIndexBroadcastSync(jsonObject.getIntValue(Key.KEY_INDEX), jsonObject.getBooleanValue(Key.KEY_REFRESH));
            ActivityManger.finishAppointActivity(MainActivity.class);
        }
    }

    public void goMainActivity(JSONObject jsonObject) {
        if (isNotNullWebView()) {
            Context context = webViewWeak.get().getContext();
            Intent intent = new Intent(context, MainActivity.class);
            intent.putExtra(Key.SID, jsonObject.getString(Key.SID));
            intent.putExtra(Key.AID, jsonObject.getString(Key.AID));
            context.startActivity(intent);
        }
    }

    public void checkUpdate() {
        ApiHelper.getApiService().version()
                .compose(RxHelper.handleResult())
                .subscribe(new RxSubscribe<JSONObject>() {
                    @Override
                    protected void _onNext(JSONObject jsonObject) {
                        if (webViewWeak.get() != null)
                            AndPermission.with(webViewWeak.get().getContext())
                                    .runtime()
                                    .permission(Permission.WRITE_EXTERNAL_STORAGE)
                                    .onDenied(data -> handUpdate(jsonObject))
                                    .onGranted(data -> handUpdate(jsonObject))
                                    .start();

                    }
                });
    }

    private void handUpdate(JSONObject jsonObject) {
        String apkUrl = jsonObject.getString("apkUrl");
//                        boolean isForce = jsonObject.getBoolean("isForce");
        boolean isForce = true;
        if (Utils.isUpdate(webViewWeak.get().getContext(), jsonObject.getString("versionName"))) {
            AlertDialog.Builder builder = new AlertDialog.Builder(webViewWeak.get().getContext())
                    .setMessage(jsonObject.getString("changeLog"));
            if (!isForce)
                builder.setNegativeButton(R.string.button_cancel, null);
            builder.setPositiveButton(R.string.button_update, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    ActivityManger.getCurActivity().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(apkUrl)));
                }
            })
                    .setCancelable(!isForce)
                    .create()
                    .show();
        }
    }

    public void changShop(JSONObject jsonObject) {
        NubyLocalBroadcastManager.sendChangSidBroadcastSync(jsonObject.getString(Key.SID), jsonObject.getString(Key.AID));
    }

    public void scanQrCode(JsCallback jsCallback) {
        if (isNotNullWebView()) {
            AndPermission.with(webViewWeak.get().getContext())
                    .runtime()
                    .permission(Permission.CAMERA)
                    .onGranted(permissions -> scan(jsCallback))
                    .onDenied(permissions -> scan(jsCallback))
                    .start();
        }
    }

    public void goCashier() {
        if (isNotNullWebView()) {
            if (Utils.isPad()) {
                Context context = webViewWeak.get().getContext();
                Intent intent = new Intent(context, CashierActivityPadActivity.class);
                context.startActivity(intent);
            } else {
                Context context = webViewWeak.get().getContext();
                Intent intent = new Intent(context, CashierActivity.class);
                context.startActivity(intent);
            }
        }
    }

    public void goSimpleCashier() {
        Context context = webViewWeak.get().getContext();
        Intent intent = new Intent(context, SimpleCashierActivity.class);
        context.startActivity(intent);
    }

    private void scan(JsCallback jsCallback) {
        QrCodeHelper.scan((Activity) webViewWeak.get().getContext(), new QrCodeListener() {
            @Override
            public void result(String result) {
                jsCallback.call(result);
            }
        });
    }

    @Override
    public void onSaveInstanceState() {
//        if (isNotNullWebView()){
//            Logger.e("onSaveInstanceState==>" + webViewWeak.get().getUrl());
//            NubyLocalBroadcastManager.unregisterReceiver(mBroadcastReceiver);
//        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (isNotNullWebView()) {
            NubyLocalBroadcastManager.unregisterReceiver(mBroadcastReceiver);
        }
    }
}
